<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="filter-container">
        <el-input placeholder="流程名称" class="filter-item search-item"
                  v-model="queryParams.model.name"/>

        <el-button @click="handleQuery" class="filter-item" plain type="primary">{{ $t('table.search') }}</el-button>
        <el-button @click="reset" class="filter-item" plain type="warning">{{ $t('table.reset') }}</el-button>
        <el-button @click="handleCreate" class="filter-item" plain type="danger" v-has-permission="['authority:application:add']">
          {{ $t("table.add") }}
        </el-button>
      </div>
      <el-table
        :data="tableData.records"
        :key="tableKey"
        @cell-click="cellClick"
        @filter-change="filterChange"
        @selection-change="onSelectChange"
        @sort-change="sortChange"
        border fit row-key="id"
        ref="table"
        style="width: 100%;"
        v-loading="loading"
      >
        <el-table-column label="名称" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.remarks }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图标" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <i :class="scope.row.icon"></i>
          </template>
        </el-table-column>
        <el-table-column label="创建人" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.createName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>


        <el-table-column :label="$t('table.operation')" align="center" column-key="operation"
                         class-name="small-padding fixed-width" fixed="right" width="250px">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-receiving"
              @click="handleClone(row)"
            >克隆</el-button>
            <i @click="handleEdit(row)" class="el-icon-edit table-operation" style="color: #2db7f5;"
               v-has-permission="['authority:application:edit']"></i>
            <i @click="handleDelete(row)" class="el-icon-delete table-operation" style="color: #f50;"
               v-has-permission="['authority:application:delete']"></i>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :limit.sync="queryParams.size"
        :page.sync="queryParams.current" :total="Number(tableData.total)"
        @pagination="fetch" v-show="tableData.total>0"/>


      <el-dialog :title="dialogProcessVisibleName===1?'新建流程':'编辑流程'" :visible.sync="open" :fullscreen="true" style="margin-top: 0">
        <div class="tpl-create-content">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="ruleForm.name" placeholder="请输入流程名称" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图标" prop="icon">
                  <e-icon-picker v-model="ruleForm.icon" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="分类" prop="classifyId">
                  <el-select v-model="ruleForm.classifyId" filterable placeholder="请选择流程分类" style="width: 100%">
                    <el-option
                      v-for="item in classifyListData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="模版" prop="tpls">
                  <el-select v-model="ruleForm.tpls" filterable multiple placeholder="请选择模版" style="width: 100%">
                    <el-option
                      v-for="item in templates"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="通知">
                  <el-select v-model="ruleForm.notice" multiple filterable clearable placeholder="请选择流程任务" style="width: 100%">
                    <el-option label="邮件" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务">
                  <el-select v-model="ruleForm.task" multiple filterable clearable placeholder="请选择流程任务" style="width: 100%">
                    <el-option
                      v-for="(item, index) in taskListData"
                      :key="index"
                      :label="item.name"
                      :value="item.full_name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述" prop="remarks">
              <el-input
                v-model="ruleForm.remarks"
                placeholder="请输入流程描述"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="流程" prop="structure">
              <div style="border-radius: 4px; overflow:hidden">
                <div>
                  <WfdDesign
                    v-if="wfdDesignRefresh"
                    ref="wfd"
                    :users="users"
                    :roles="roles"
                    :departments="departments"
                    :tasks="taskListData"
                    :templates="ruleForm.tpls"
                    :templates-base="templates"
                    :data="ruleForm.structure"
                    :height="600"
                    :lang="lang"
                  />
                </div>
              </div>
            </el-form-item>
          </el-form>
          <div style="text-align: center; margin-top: 20px">
            <el-button type="primary" @click="dialogProcessVisibleName===1?submitForm('ruleForm'):editForm('ruleForm')">提交</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import processApi from '@/api/process/admin/process'
import classifyApi from '@/api/process/admin/classify.js'
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog'
import {downloadFile, initQueryParams} from '@/utils/commons'
// import {EIcon} from 'e-icon-picker';
import templateApi from '@/api/process/admin/template'
import taskApi from '@/api/process/admin/task'
 import userApi from '@/api/User'
import roleApi from '@/api/Role'
import stationApi from '@/api/Station'

export default {
  name: 'ProcessManager',
  directives: {elDragDialog},
  components: {Pagination,
    WfdDesign: () => import('@/components/wfd/components/Wfd')
  },
  data() {
    return {
      queryParams: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      structureValue: [],
      users: [],
      roles: [],
      groups: [],
      departments: [],
      templates: [],
      taskListData: [],
      wfdDesignRefresh: true,
      classifyListData: [],
      dialogProcessVisibleName: 1,
      processValueList: [],
      listQuery: {
        page: 1,
        per_page: 10
      },


      queryParams: initQueryParams({
        model: {}
      }),
      selection: [],
      tableKey: 0,
      tableData: {
        total: 0
      },


      lang: 'zh',
      ruleForm: {},
      rules: {
        icon: [
          { required: true, message: '请输入流程图标', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入流程名称', trigger: 'blur' }
        ],
        classifyId: [
          { required: true, message: '请选择流程分类', trigger: 'blur, change' }
        ],
        tpls: [
          { required: true, message: '请选择模版', trigger: 'blur, change' }
        ],
        structure: [
          { required: true, message: '请设计流程', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入流程描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取任务列表
    getTaskList() {
      console.log("任务列表")
      this.queryParams.size=999
      taskApi.taskList(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.taskListData = res.data.records;
        }
        this.loading = false
      }).finally(() => this.loading = false);

    },
    // 获取流程分类列表
    getClassifyList() {

      this.queryParams.size=999
      classifyApi.page(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.classifyListData = res.data.records;
        }
        this.loading = false
      }).finally(() => this.loading = false);

    },
    // 获取模版列表
    getTemplates() {
      this.queryParams.size=999
      templateApi.templateList(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.templates = res.data.records;
        }
        this.loading = false
      }).finally(() => this.loading = false);

    },
    // 获取用户
    getUsers() {
      userApi.find().then(response=>{
        console.log("用户数据",  response.data.data);
        this.users = response.data.data
      })

    },
    getRoles() {
      roleApi.page(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.roles = res.data.records;
        }
        this.loading = false
      }).finally(() => this.loading = false);

    },
    // 获取部门
    getDepartments() {
      stationApi.page(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.departments = res.data.records;
        }
        this.loading = false
      }).finally(() => this.loading = false);

    },
    /** 查询流程列表 */
    getList() {
      this.loading = true
      this.fetch();
    },
    getProcessInitData() {
      this.getClassifyList()
      this.getTemplates()
      this.getUsers()
      this.getRoles()
      this.getDepartments()
      this.getTaskList()
    },
    handleCreate() {
      this.getProcessInitData()
      this.ruleForm = {
        id: undefined,
        name: '',
        tpls: [],
        structure: { 'edges': [], 'nodes': [], 'groups': [] },
        classifyId: '',
        task: [],
        notice: [1],
        icon: '',
        remarks: ''
      }
      this.dialogProcessVisibleName = 1
      this.open = true
      this.wfdDesignRefresh = false
      this.$nextTick(() => {
        this.wfdDesignRefresh = true
      })
    },
    handleEdit(row) {
      this.dialogProcessVisibleName = 2
      this.getProcessInitData()
      this.wfdDesignRefresh = false
      this.open = true
      processApi.processDetails({
        id: row.id
      }).then(response => {
        let processInfoDetails = response.data.data
        this.ruleForm = {
          id: processInfoDetails.id,
          name: processInfoDetails.name,
          tpls: processInfoDetails.tpls,
          structure: processInfoDetails.structure,
          classifyId: processInfoDetails.classifyId,
          task: processInfoDetails.task,
          notice: processInfoDetails.notice,
          icon: processInfoDetails.icon,
          remarks: processInfoDetails.remarks
        }
        this.wfdDesignRefresh = false
        this.$nextTick(() => {
          this.wfdDesignRefresh = true
        })
      })
    },
    verifyProcess(structureValue) {
      for (var r of structureValue.nodes) {
        if (r.sort === undefined || r.sort === null || r.sort === '') {
          return '流程节点顺序不能为空'
        } else if (r.label === undefined || r.label === null || r.label === '') {
          return '流程节点标题不能为空'
        }
        if (r.clazz === 'userTask' || r.clazz === 'receiveTask') {
          if (r.assignType === undefined || r.assignType === null || r.assignType === '') {
            return '审批节点或处理节点的处理人类型不能为空'
          } else if (r.assignValue === undefined || r.assignValue === null || r.assignValue === '' || r.assignValue.length === 0) {
            return '审批节点或处理节点的处理人不能为空'
          }
        }
      }
      for (var e of structureValue.edges) {
        if (e.sort === undefined || e.sort === null || e.sort === '') {
          return '流转顺序不能为空'
        } else if (e.label === undefined || e.label === null || e.label === '') {
          return '流转标题不能为空'
        } else if (e.flowProperties === undefined || e.flowProperties === null || e.flowProperties === '') {
          return '流转属性不能为空'
        }
      }
      return ''
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var structureValue = this.$refs.wfd.graph.save()

          var r = this.verifyProcess(structureValue)
          if (r !== '') {
            this.$message.error(r)
            return
          }
          console.log("structureValue====", structureValue);
          if (structureValue.nodes.length > 0 && structureValue.edges.length > 0) {
            this.ruleForm.structure = structureValue
            processApi.createProcess(this.ruleForm).then(response => {
              this.getList()
              this.open = false
            })
          } else {
            this.$message.error('没有流程数据，请完善流程')
          }
        }
      })
    },
    editForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var structureValue = this.$refs.wfd.graph.save()
          var r = this.verifyProcess(structureValue)
          if (r !== '') {
            this.$message.error(r)
            return
          }
          if (structureValue.nodes.length > 0 && structureValue.edges.length > 0) {
            processApi.updateProcess({
              id: this.ruleForm.id,
              name: this.ruleForm.name,
              tpls: this.ruleForm.tpls,
              structure: structureValue,
              classifyId: this.ruleForm.classifyId,
              task: this.ruleForm.task,
              notice: this.ruleForm.notice,
              icon: this.ruleForm.icon,
              remarks: this.ruleForm.remarks
            }).then(response => {
              this.getList()
              this.open = false
            })
          } else {
            this.$notify({
              title: '错误',
              message: '没有流程数据，请完善流程',
              type: 'error'
            })
          }
        }
      })
    },
    handleQuery() {

      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        processApi.deleteProcess({
          id: row.id
        }).then(response => {
          if (response !== undefined) {
            this.getList()
            this.$message({
              type: 'success',
              message: '流程已删除!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange() {},
    handleSave(values) {
      if (values.list.length > 0) {
        this.ruleForm.form_structure = values
      } else {
        this.ruleForm.form_structure = ''
      }
    },
    handleClone(row) {
      this.$confirm(`确认克隆流程 < ${row.name} > ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        processApi.cloneProcess(row.id).then(() => {
          this.getList()
          this.$message({
            type: 'success',
            message: '流程已克隆!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    fetch(params = {}) {
      this.loading = true;
      if (this.queryParams.timeRange) {
        this.queryParams.extra.createTime_st = this.queryParams.timeRange[0];
        this.queryParams.extra.createTime_ed = this.queryParams.timeRange[1];
      }
      this.queryParams.current = params.current ? params.current : this.queryParams.current;
      this.queryParams.size = params.size ? params.size : this.queryParams.size;
      processApi.processList(this.queryParams).then(response => {
        const res = response.data;
        console.log("分页查询", res);
        if (res.isSuccess) {
          this.tableData = res.data;
        }
        this.loading = false
      }).finally(() => this.loading = false);
    },
    search() {
      this.fetch({
        ...this.queryParams,
      })
    },
    reset() {
      this.queryParams = initQueryParams({
        model: {}
      });
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.search()
    },
    sortChange(val) {
      this.queryParams.sort = val.prop;
      this.queryParams.order = val.order;
      if (this.queryParams.sort) {
        this.search();
      }
    },
    filterChange(filters) {
      for (const key in filters) {
        if (key.includes('.')) {
          const val = {};
          val[key.split('.')[1]] = filters[key][0];
          this.queryParams.model[key.split('.')[0]] = val;
        } else {
          this.queryParams.model[key] = filters[key][0]
        }
      }
      this.search()
    },
    onSelectChange(selection) {
      this.selection = selection
    },
    cellClick(row, column) {
      if (column['columnKey'] === "operation") {
        return;
      }
      if (column['columnKey'] === "clientId") {
        copy(row[column.property]);
        this.$message({
          message: this.$t('tips.copySelected'),
          type: 'success'
        })
        return;
      }

      let flag = false;
      this.selection.forEach((item) => {
        if (item.id === row.id) {
          flag = true;
          this.$refs.table.toggleRowSelection(row);
        }
      })
      if (!flag) {
        this.$refs.table.toggleRowSelection(row, true);
      }
    },



  }
}
</script>
